package com.hpplay.sdk.source.test.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.EditText;
import android.widget.ImageView;

import com.hpplay.sdk.source.api.LelinkSourceSDK;
import com.hpplay.sdk.source.bean.SinkTouchEventArea;
import com.hpplay.sdk.source.test.DemoApplication;
import com.hpplay.sdk.source.test.Logger;
import com.hpplay.sdk.source.test.R;
import com.hpplay.sdk.source.test.constants.KeyEventName;
import com.hpplay.sdk.source.test.utils.ScreenUtil;

public class ReverseControlActivity extends Activity {
    private static final String TAG = "SinkKeyEventTestActivi";

    private ImageView mUpIv;
    private ImageView mDownIv;
    private ImageView mLeftIv;
    private ImageView mRightIv;
    private ImageView mOkIv;
    private ImageView mBackIv;
    private ImageView mSettingsTv;
    private EditText mScaleModulusEt;

    private long firstDownTime = -1;
    private int preEventAction = -1;

    public static void show(Context context) {
        context.startActivity(new Intent(context, ReverseControlActivity.class));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reverse_control);

        mUpIv = (ImageView) findViewById(R.id.iv_key_up);
        mDownIv = (ImageView) findViewById(R.id.iv_key_down);
        mLeftIv = (ImageView) findViewById(R.id.iv_key_left);
        mRightIv = (ImageView) findViewById(R.id.iv_key_right);
        mOkIv = (ImageView) findViewById(R.id.iv_key_ok);
        mBackIv = (ImageView) findViewById(R.id.iv_key_back);
        mSettingsTv = (ImageView) findViewById(R.id.iv_key_settings);

        mScaleModulusEt = findViewById(R.id.et_scale_modulus);
        mScaleModulusEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                setSinkTouchEventListener();
            }
        });
        setSinkTouchEventListener();
        setSinkKeyEventListener();
    }

    private String getKeyName(int keyCode) {
        String keyName = KeyEventName.KeyEventMap.getInstance().get(keyCode);
        if (TextUtils.isEmpty(keyName)) {
            keyName = KeyEventName.KEY_NAME_UNKNOWN;
        }
        return keyName;
    }

    private void showByAction(ImageView imageView, int action) {
        DemoApplication.runOnUI(() -> imageView.setBackgroundColor(action == KeyEvent.ACTION_UP ? Color.TRANSPARENT : Color.GRAY));
    }

    private void setSinkTouchEventListener() {
        LelinkSourceSDK.getInstance().registerSinkTouchEvent();
        int[] screenSize = ScreenUtil.getRelScreenSize(this);
        SinkTouchEventArea sinkTouchEventArea = new SinkTouchEventArea(screenSize[0], screenSize[1]);
        float scaleModulus = 0f;
        if (!TextUtils.isEmpty(mScaleModulusEt.getText())) {
            scaleModulus = Float.parseFloat(mScaleModulusEt.getText().toString());
        }
        LelinkSourceSDK.getInstance().setSinkTouchEventListener(sinkTouchEventArea, scaleModulus, motionEvent -> {
            Logger.i(TAG, "onTouchEvent: " + motionEvent.toString());
            dispatchTouchEvent(motionEvent);
        });
    }

    private void setSinkKeyEventListener() {
        LelinkSourceSDK.getInstance().registerSinkKeyEvent();
        LelinkSourceSDK.getInstance().setSinkKeyEventListener((keyEvent) -> {
            int keyCode = keyEvent.getKeyCode();
            int action = keyEvent.getAction();
            if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
                DemoApplication.runOnUI(() -> getWindow().getDecorView().dispatchKeyEvent(keyEvent));
                return;
            }
            Logger.i(TAG, "onEvent: keyCode: " + keyCode + " action: " + action);
            ImageView targetView = null;
            switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_UP:
                    targetView = mUpIv;
                    break;
                case KeyEvent.KEYCODE_DPAD_DOWN:
                    targetView = mDownIv;
                    break;
                case KeyEvent.KEYCODE_DPAD_LEFT:
                    targetView = mLeftIv;
                    break;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                    targetView = mRightIv;
                    break;
                case KeyEvent.KEYCODE_DPAD_CENTER:
                    targetView = mOkIv;
                    break;
                case KeyEvent.KEYCODE_BACK:
                    targetView = mBackIv;
                    break;
                case KeyEvent.KEYCODE_MENU:
                    targetView = mSettingsTv;
                    break;
            }

            // 判断是否第一次按下
            if (preEventAction != KeyEvent.ACTION_DOWN && action == KeyEvent.ACTION_DOWN) {
                firstDownTime = System.currentTimeMillis();
            }

            // 判断是否是第一次抬起
            if (preEventAction == KeyEvent.ACTION_DOWN && action == KeyEvent.ACTION_UP) {
                String keyName = getKeyName(keyCode);
                if (System.currentTimeMillis() - firstDownTime > 1500) {
                    DemoApplication.toast(keyName + ": long clicked");
                } else {
                    DemoApplication.toast(keyName + ": clicked");
                }
            }

            preEventAction = action;

            if (targetView == null) {
                return;
            }
            showByAction(targetView, action);
        });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Logger.i(TAG, "onTouchEvent: downTime: " + event.getDownTime() + ", eventTime: " + event.getEventTime() +
                ", action: " + event.getAction() + ", pointerCount: " + event.getPointerCount() + ", pressure: " + event.getPressure() +
                ", size: " + event.getSize() + ", metaState: " + event.getMetaState() + ", xPrecision: " + event.getXPrecision() +
                ", yPrecision: " + event.getYPrecision() + ", edgeFlag: " + event.getEdgeFlags());
        return super.onTouchEvent(event);
    }
}